package cn.sciento.wechat.enterprise.service.impl;

import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import cn.sciento.wechat.enterprise.dto.TokenDTO;
import cn.sciento.wechat.enterprise.enums.SecretTypeEnum;
import cn.sciento.wechat.enterprise.service.WechatTokenService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.client.RestTemplate;

public class WechatTokenServiceImpl implements WechatTokenService {
  protected static final String WX_TOKEN_KEY = "hips:token:wechat-enterprise";
  
  @Resource(name = "wdRedisTemplate")
  protected RedisTemplate redisTemplate;
  
  @Resource(name = "wdRestTemplate")
  protected RestTemplate restTemplate;
  
  public TokenDTO getTokenWithCache(String corpId, String corpSecret, SecretTypeEnum secretTypeEnum) {
    String key = "hips:token:wechat-enterprise:" + corpId;
    if (secretTypeEnum.equals(SecretTypeEnum.APP)) {
      key = key + ":" + SecretTypeEnum.APP.getCode();
    } else if (secretTypeEnum.equals(SecretTypeEnum.CORP)) {
      key = key + ":" + SecretTypeEnum.CORP.getCode();
    } 
    ValueOperations<String, TokenDTO> valueOperations = this.redisTemplate.opsForValue();
    if (this.redisTemplate.hasKey(key).booleanValue()) {
      TokenDTO tokenDTO1 = (TokenDTO)valueOperations.get(key);
      return tokenDTO1;
    } 
    TokenDTO tokenDTO = (TokenDTO)this.restTemplate.getForObject("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpId + "&corpsecret=" + corpSecret, TokenDTO.class);
    if (tokenDTO != null && StringUtils.isNotBlank(tokenDTO.getAccess_token())) {
      int expires_in = tokenDTO.getExpires_in();
      valueOperations.set(key, tokenDTO);
      this.redisTemplate.expire(key, expires_in, TimeUnit.SECONDS);
    } 
    return tokenDTO;
  }
  
  public TokenDTO getToken(String corpId, String corpSecret) {
    return (TokenDTO)this.restTemplate.getForObject("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpId + "&corpsecret=" + corpSecret, TokenDTO.class);
  }
  
  public TokenDTO getTokenFromThirdPart(String authUrl) {
    return (TokenDTO)this.restTemplate.getForObject(authUrl, TokenDTO.class);
  }
}
